package com.example.music_project.service;

import com.example.music_project.mapper.MusicMapper;
import com.example.music_project.model.MusicInfo;
import com.example.music_project.model.User;
import com.example.music_project.tools.Constant;
import com.example.music_project.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.Oneway;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class MusicService {
    @Value("${music.local.path}")
    public String filePath;
    @Autowired
    MusicMapper musicMapper;
    //上传音乐
    public Result<MusicInfo> upFile(String singer, MultipartFile file, HttpServletRequest request
    , HttpServletResponse response){
        Result<MusicInfo> result = new Result<>();
        //判断用户是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION)== null) {
            return result.fail("用户未登录");
        }
        //取出用户session
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        Integer userId = user.getId();
        //检查上传的文件是否是MP3文件

        //检查当前上传的音乐在服务器中是否存在

        //上传文件到本地
        String originalFilename = file.getOriginalFilename();// ***.mp3
        String path = filePath + originalFilename;
        System.out.println("path:" + path);
        File dest = new File(path);
        if(!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("服务器上传文件失败");
            return result.fail("服务器上传文件失败");
        }
        //将数据插入到数据库中
        // 1. 获取歌曲名
        int index = originalFilename.lastIndexOf(".");
        String title = originalFilename.substring(0, index);
        //封装
        String url = "/music/listen?path=" + title;
        System.out.println("url:" + url);
        MusicInfo music = new MusicInfo();
        music.setTitle(title);
        music.setSinger(singer);
        music.setUrl(url);
        music.setUserId(userId);
        // 2.上传数据库
        Integer ret = musicMapper.insertFile(music);
        if(ret < 1) {
            log.error("数据库上传失败");
            //删除本地文件
            dest. delete();
            return result.fail("数据库上传失败");
        }

        return result.success(music);
    }
    //播放音乐
    public ResponseEntity<byte[]> listenLogic(String path) {
        File file = new File(filePath + path);
        System.out.println("路径："+file.toPath());
        byte[] bytes = null;
        try {
            bytes = Files.readAllBytes(file.toPath());
            if(bytes == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 删除音乐
    public Result<Object> deleteLogic(Integer id) {
        Result<Object> result = new Result<>();
        log.info("id:{}", id);
//        //判断用户是否登录
//        HttpSession session = request.getSession(false);
//        if(session == null || session.getAttribute(Constant.USER_SESSION)== null) {
//            return result.fail("用户未登录");
//        }
//        //取出用户session
//        User user = (User)session.getAttribute(Constant.USER_SESSION);
//        Integer userId = user.getId();
        // 1. 查看数据库中是否存在
        MusicInfo musicInfo = musicMapper.queryById(id);
        if(musicInfo == null) {
            return result.fail("数据库中没有该歌曲");
        }
        // 2. 删除数据库中的记录
        Integer ret = musicMapper.deleteMusic(id);
        if(ret < 1) {
            return result.fail("数据库删除失败");
        }
        //3. 判断该音乐是否被收藏

        // 3.删除服务器中歌曲文件
        String title = musicInfo.getTitle();
        String path = filePath + title + ".mp3";
        File file = new File(path);
        if(file.delete()) {
            return result.success("音乐删除成功");
        }else {
            return result.fail("音乐删除失败");
        }

    }
    //批量删除音乐
    public Result<Object> deleteAllLogic(List<Integer> id) {
        Result<Object> result = new Result<>();
        int sum = 0;
        for(int i = 0; i < id.size(); i++) {
            MusicInfo musicInfo = musicMapper.queryById(id.get(i));
            if(musicInfo == null) {
                log.error("数据库中没有该歌曲");
                return result.fail("数据库中没有该歌曲");
            }
            // 2. 删除记录
            Integer ret = musicMapper.deleteMusic(id.get(i));
            if(ret < 1) {
                log.error("数据库删除失败");
                return result.fail("数据库删除失败");
            }
            // 3.删除服务器中歌曲文件
            String title = musicInfo.getTitle();
            String path = filePath + title + ".mp3";
            File file = new File(path);
            if(file.delete()) {
                sum += 1;
            }else {
                log.error("音乐删除失败");
                log.error("sum:{}",sum);
                return result.fail("音乐删除失败");
            }
        }
        if(sum != id.size()) {
            log.error("批量删除失败");
            return result.fail("批量删除失败");
        }
        return result.success("批量删除成功");
    }
    //查询音乐
    public List<MusicInfo> queryMusicLogic(String musicName) {
        log.info("musicName:{}", musicName);

        List<MusicInfo> list = null;
        if(musicName == null) {
            //查询全部
            list = musicMapper.queryAllMusic();
        }else {
            list = musicMapper.queryByMusicName(musicName);
        }
        return list;
    }

    //收藏音乐逻辑
    public Result<Object> collectLogic(Integer musicId, HttpServletRequest request) {
        Result<Object> result = new Result<>();
        if(musicId == null) return result.fail("id为空");
        //判断是否已经登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION)== null) {
            return result.fail("用户未登录");
        }
        //取出用户session
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        Integer userId = user.getId();
        //查询数据库是否已经收藏
        MusicInfo musicInfo = musicMapper.queryByUserIdAndMusicId(userId, musicId);
        if(musicInfo != null) {
            log.error("用户已经收藏");
            return result.fail("用户已经收藏");
        }
        //进行收藏
        Integer ret = musicMapper.collectMusic(userId, musicId);
        if(ret < 1) {
            log.error("收藏失败");
            return result.fail("收藏失败");
        }
        return result.success("收藏成功");
    }

    //查询收藏的音乐
    public Result<Object> queryForCollectLogic(String musicName, HttpServletRequest request) {
        //判断用户是否登录
        Result<Object> result = new Result<>();
        //T判断是否已经登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION)== null) {
            return result.fail("用户未登录");
        }
        //取出用户session
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        Integer userId = user.getId();
        List<MusicInfo> list = new ArrayList<>();
        if(musicName == null) {
            //如果为空，则返回所有的收藏音乐
           list = musicMapper.queryAllCollect(userId);
           log.info("查询到所有收藏的音乐");
           return result.success(list);
        }
        //查询指定的音乐
        list = musicMapper.queryPoint(userId, musicName);
        log.info("list:{}", list.toString());
        return result.success(list);
    }

    //取消收藏
    public Result<Object> deleteCollectLogic(Integer musicId, HttpServletRequest request) {
        Result<Object> result = new Result<>();
        //检查是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USER_SESSION)== null) {
            return result.fail("用户未登录");
        }
        //取出用户session
        User user = (User)session.getAttribute(Constant.USER_SESSION);
        Integer userId = user.getId();
        //取消数据库收藏
        Integer ret = musicMapper.deleteCollectMusic(userId, musicId);
        if(ret < 1) {
            return result.fail("取消收藏失败");
        }
        log.info("取消收藏成功");
        return result.success("取消收藏成功");
    }
}

